<?php

namespace App\Models\Chanjet;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class TplusExpenseVoucher extends Model
{
    protected $table = 'tplus_expense_voucher';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    public static function getList(Request $request, $memberinfo, $isgetall)
    {
        $cpid = $memberinfo['cpid'] ?? 0;
        $where[] = ['cpid',$cpid];
        //单据编号
        if($request->voucher_code){
            $where[] = ['voucher_code',$request->voucher_code];
        }
        //业务类型 37 往来费用 38 现金费用
        if(!empty($request->business_type)){
            $business_type_arr = [
                '37' => '往来费用',
                '38' => '现金费用',
            ];
            if(isset($business_type_arr[$request->business_type])){
                $where[] = ['business_type',$business_type_arr[$request->business_type]];
            }
        }
        //票据类型  00:运费发票 , 01:专用发票 , 02:收据，03:普通发票-内含, 04:普通发票
        if(!empty($request->bill_type)){
            $bill_type_arr = [
                '00' => '运费发票',
                '01' => '专用发票',
                '02' => '收据',
                '03' => '普通发票-内含',
                '04' => '普通发票',
            ];
            if(isset($bill_type_arr[$request->bill_type])){
                $where[] = ['bill_type',$bill_type_arr[$request->bill_type]];
            }
//            $where[] = ['bill_type','like','%'.$request->bill_typ.'%'];
        }
        //往来单位
        if(!empty($request->company_name_abbreve)){
            $where[] = ['company_name_abbreve','like','%'.$request->company_name_abbreve.'%'];
        }

        //单据状态  未审 生效
        if(!empty($request->voucher_status)){
            $where[] = ['voucher_status',$request->voucher_status];
        }

        $query = self::with("info")->where($where)->orderBy('voucher_time', 'desc');
        //单据日期  范围值
        if(isset($request->start_time) && isset($request->end_time)){
            $start_time = isTimestamp($request->start_time)?$request->start_time:strtotime($request->start_time);
            $end_time = isTimestamp($request->end_time)?$request->end_time:strtotime($request->end_time);
            $query->whereBetween('voucher_time',[$start_time,$end_time]);
        }
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }
    public function info()
    {
        return $this->hasMany(TplusExpenseVoucherInfo::class,'main_id','id');
    }
}
